package com.example.myprojectoffeixue;

import android.app.Activity;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import org.apache.http.entity.StringEntity;

import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import cn.jpush.android.api.JPushInterface;

public class ReginActivity extends Activity  {
    //注册界面
    public EditText et;
    public EditText et1;
    public EditText et2;
    public EditText et3;
    public TextView tv;
    LinearLayout root;
    LinearLayout root1;
    int hight=0;
    boolean flag=false;
    Handler hand = new Handler() {

        public void handleMessage(android.os.Message msg) {
            if (msg.what == 0) {
                String d = (String) msg.obj;
                tv.setText(d);
                if ("1".equals(d)) {
                    tv.setText("获取验证码");
                    tv.setClickable(true);
                }


            }


        }

    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        setContentView(R.layout.activity_regin);
        info();
    }

    //获取控件
    private void info() {
        et = (EditText) findViewById(R.id.et_regin);
        et1 = (EditText) findViewById(R.id.et1_regin);
        et2 = (EditText) findViewById(R.id.et2_regin);
        et3 = (EditText) findViewById(R.id.et3_regin);

       et.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){//获得焦点
                  flag=true;
                }
            }
        });


        et1.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){//获得焦点
                    flag=true;
                }
            }
        });
        et2.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){//获得焦点
                    flag=true;
                }
            }
        });


        et3.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){//获得焦点
                    flag=true;
                }
            }
        });

        tv = (TextView) findViewById(R.id.tv_regin);
        root1 = (LinearLayout) findViewById(R.id.root);
        root = (LinearLayout) findViewById(R.id.root2);
    }

    //根据Id的不同添加点击的监听事件
    public void click(View v) {

        switch (v.getId()) {
            //发送验证码，在这之前使用正则表达式对手机号进行验证
            case R.id.tv_regin:

                if ("".equals(et.getText().toString())) {
                    HttpConnection.showToast(getBaseContext(), "请输入手机号");

                } else {
                    UserClass u = new UserClass();
                    u.mobile = et.getText().toString();
                    String j = JSON.toJSONString(u);
                    j = AESUtil.encrypt(j);
                    HttpUtils httpUtils = new HttpUtils();
                    RequestParams params = new RequestParams();
                    params.setHeader("Content-Type", "application/json");
                    try {
                        params.setBodyEntity(new StringEntity(j, "utf-8"));
                    } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    httpUtils.send(HttpMethod.POST, "http://" + UserClass.ServerIP + "/FXMobiServer/user/sendCaptcha", params,
                            new RequestCallBack<String>() {
                                @Override
                                public void onFailure(HttpException arg0, String arg1) {
                                    HttpConnection.showToast(getBaseContext(), "网络异常");
                                    tv.setClickable(true);

                                }

                                @Override
                                public void onSuccess(ResponseInfo<String> arg0) {
                                    if (arg0.result != null && !("".equals(arg0.result))) {

                                        arg0.result = AESUtil.decrypt(arg0.result);
                                        GateWay p = JSON.parseObject(arg0.result, GateWay.class);
                                        if (0 == p.status) {
                                            HttpConnection.showToast(getBaseContext(), "验证码已发送，请注意查收");
                                            tv.setClickable(false);
                                            new Thread() {

                                                public void run() {

                                                    for (int i = 60; i > 0; i--) {
                                                        Message msg = new Message();
                                                        msg.what = 0;
                                                        msg.obj = i + "";
                                                        hand.sendMessage(msg);
                                                        try {
                                                            sleep(1000);
                                                        } catch (InterruptedException e) {
                                                            // TODO Auto-generated catch block
                                                            e.printStackTrace();
                                                        }

                                                    }


                                                }

                                                ;


                                            }.start();
                                        } else {

                                            HttpConnection.showToast(getBaseContext(), p.msg);
                                        }
                                    } else {
                                        HttpConnection.showToast(getBaseContext(), "服务器错误");
                                    }

                                }
                            });
                }
                break;

            case R.id.iv_regin:
                //注册按钮，点击将数据传给后台，注册成功直接跳转到登录界面
                HttpUtils httpUtils = new HttpUtils();
                if ("".equals(et.getText().toString())) {
                    HttpConnection.showToast(getBaseContext(), "请输入手机号");
                } else if ("".equals(et1.getText().toString())) {
                    HttpConnection.showToast(getBaseContext(), "请输入验证码");
                } else if ("".equals(et2.getText().toString())) {
                    HttpConnection.showToast(getBaseContext(), "请输入密码");
                } else if (!stringFilter(et2.getText().toString())) {
                    HttpConnection.showToast(getBaseContext(), " 密码只能输入8—15位数字字母下划线");
                } else if ("".equals(et3.getText().toString()) || !et2.getText().toString().equals(et3.getText().toString())) {
                    HttpConnection.showToast(getBaseContext(), "请确认密码");
                } else {
                    String id = JPushInterface.getRegistrationID(getBaseContext());
                    UserClass f = new UserClass();
                    f.regId = id;
                    f.mobile = et.getText().toString();
                    f.captcha = et1.getText().toString();
                    f.password = et2.getText().toString();
                    f.os = "Android";
                    String k = JSON.toJSONString(f);
                    k = AESUtil.encrypt(k);
                    RequestParams param = new RequestParams();
                    param.setHeader("Content-Type", "application/json");
                    try {
                        param.setBodyEntity(new StringEntity(k, "utf-8"));
                    } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    httpUtils.send(HttpMethod.POST, "http://" + UserClass.ServerIP + "/FXMobiServer/user/register", param,
                            new RequestCallBack<String>() {

                                @Override
                                public void onFailure(HttpException arg0, String arg1) {
                                    HttpConnection.showToast(getBaseContext(), "网络异常");

                                }
                                @Override
                                public void onSuccess(ResponseInfo<String> arg0) {
                                    if (arg0.result != null && !("".equals(arg0.result))) {
                                        arg0.result = AESUtil.decrypt(arg0.result);
                                        GateWay p = JSON.parseObject(arg0.result, GateWay.class);
                                        if (0 == p.status) {
                                            finish();
                                        } else {
                                            HttpConnection.showToast(getBaseContext(), p.msg);
                                        }
                                    } else {

                                        HttpConnection.showToast(getBaseContext(), "服务器错误");
                                    }
                                }
                            });

                }

                break;

            default:
                break;
        }

    }



    @Override
    protected void onStart() {
       root1.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        Rect r = new Rect();
                         root1.getWindowVisibleDisplayFrame(r);
                        int screenHeight =  root1.getRootView().getHeight();
                        int heightDifference = screenHeight - (r.bottom);
                        if(flag){
                        if (heightDifference > 200) {
                            LinearLayout.LayoutParams lp1 = (LinearLayout.LayoutParams) root.getLayoutParams();
                            Log.d("sizeHight",screenHeight+"");
                            lp1.topMargin = -screenHeight/6;
                            root.requestLayout();
                        } else {
                            LinearLayout.LayoutParams lp1 = (LinearLayout.LayoutParams) root.getLayoutParams();
                            lp1.topMargin = 30;
                            root.requestLayout();
                        }
                    }}
                });
        super.onStart();
    }

    public static boolean stringFilter(String str) throws PatternSyntaxException {
        // 只允许字母和数字
        String regEx = "^[a-zA-Z0-9]{8,15}+$";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.matches();
    }



}